<?php
require_once("SimilarMusic.php");
/**
 * Handles retrival of data from musicbrainz.org
 * 
 * @author Magnus Stoveland <mstoveland@gmail.com>
 */
class MusicBrainz 
{
    
    function getSimilarArtists($artistName) {
        if(!MusicBrainz::getSimilarArtistsFromCache($artistName)) {
            $similarArr = MusicBrainz::getSimilarArtistsFromSource($artistName);
            MusicBrainz::_writeCache($artistName, $similarArr);
        }
    }
    
    /**
     * @param $artistName
     * @return array with SimilarMusic objects 
     */
    function getSimilarArtistsFromSource($artistName) {      
        // 1. Parse artistname xml to get the unique mbid
        $xml = simplexml_load_file("http://musicbrainz.org/ws/1/artist/?type=xml&name=".urlencode($artistName));
        $artistAttr = $xml->{"artist-list"}->artist[0]->attributes(); 
        // 2. Always use the first artist alternative (temp solution?) and get the link to its similar artist page.
        $profilePage = file_get_contents("http://musicbrainz.org/show/artist/?mbid=".$artistAttr[0]);
        $pattern = "<a href=\"([^\"]*)\" title=\"Similar Artists\">Similar&nbsp;artists<\/a>";
        preg_match("/".$pattern."/iU", $profilePage, $matches);
        $simlarArtistsUrl = "http://musicbrainz.org".$matches[1];  
        // 3. Parse the similar artist page
        $similarArtistsPage = file_get_contents($simlarArtistsUrl);
        $pattern = "<td class=\"left\">[^<]*<a href=\"([^\"]*)\">(.*)<\/a><\/td>[^<]*<td style=\"padding: 0px 40px\">(.*)<\/td>";
        preg_match_all("/".$pattern."/siU", $similarArtistsPage, $matches);
        $artistNamesArr = $matches[2];
        $similarPercentageArr = $matches[3];
        foreach($artistNamesArr as $i => $artistName) {
            $SimilarMusic = new SimilarMusic();
            $SimilarMusic->artist = $artistName;
            //TODO: get te mbid!
            $SimilarMusic->percentage = trim(str_replace("%", "", $similarPercentageArr[$i]));
            $out[] = $SimilarMusic;
        }
        return $out;
    }
    
    function getSimilarArtistsFromCache($artistName) {
        $file = "./cache/MusicBrainz/".urlencode($artistName);
        $fp = @fopen($file, "r");
        if($fp) {
            foreach(file($file) as $line) {
                $lineArr = explode(",", $line);
                $SimilarMusic = new SimilarMusic();
                $SimilarMusic->percentage = $lineArr[0];
                $SimilarMusic->mbid = $lineArr[1];
                $SimilarMusic->artist = $lineArr[2];
            }
        } else {
            return false;
        }
    }
   
    
    /**
     * @param string $artistName (not urlencoded)
     * @param array $similarArr 
     */
    function _writeCache($artistName, $similarArr) {
        $data = "";
        foreach($similarArr as $SimilarMusic) {
            $data .= $SimilarMusic->percentage.",".$SimilarMusic->mbid.",".$SimilarMusic->artist."\n";
        }
        $file = "./cache/MusicBrainz/".urlencode($artistName);
        $fp = @fopen($file, "w");
        if ($fp) {
           $result = fwrite($fp, $data);
           fclose($fp);
        } else {
            trigger_error("Unable to open file for writing: ".$file, E_USER_ERROR);
        }
        Info::add($result." bytes written");
        return; 
    }
}
?>